package com.andersen.web.validating;

import com.andersen.web.beans.EmplDataCommandForm;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Created by Georg on 2/19/14.
 */

@Component
public class EmplDataValidator implements Validator {

    @Override
    public boolean supports(Class type) {
        return EmplDataCommandForm.class.isAssignableFrom(type);
    }

    @Override
    public void validate(Object obj, Errors errors) {

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "id",
                "required.id", "Field name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name",
                "required.name", "Field name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "surname",
                "required.surname", "Field name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "patronymic",
                "required.patronymic", "Field name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "position",
                "required.position", "Field name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "skype",
                "required.skype", "Field name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "phone",
                "required.phone", "Field name is required.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "discharged",
                "required.discharged", "Field name is required.");

        EmplDataCommandForm fmt = (EmplDataCommandForm)obj;

        if ("NONE".equals(fmt.getOfficeId())) {
            errors.rejectValue("officeId","required.officeId");
        }
        if (fmt.getSkype() != null && (!fmt.getSkype().isEmpty()) && fmt.getSkype().matches("^.*[^a-zA-Z0-9.].*$")) {
            errors.rejectValue("skype", "incorrect.skype");
        }
        String phn = fmt.getPhone();
        if (phn != null && !phn.isEmpty()) {
            if (phn.charAt(0) == '+') phn = phn.substring(1);
            if (phn.matches("^.*[^0-9].*$")) {
                errors.rejectValue("phone", "incorrect.phone");
            }
        }
    }

}
